package org.jeecg.modules.htxincailiao.analytics.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.contant.HTClient;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.IPInfo;
import org.jeecg.common.util.IPUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.htxincailiao.account.entity.HTPlatformUser;
import org.jeecg.modules.htxincailiao.account.service.IHTAccountService;
import org.jeecg.modules.htxincailiao.analytics.domain.dto.HTPlatformVisitUpdateDTO;
import org.jeecg.modules.htxincailiao.analytics.domain.vo.HTPlatformClientVisitDistributionVO;
import org.jeecg.modules.htxincailiao.analytics.domain.vo.HTPlatformUserVisitDistributionVO;
import org.jeecg.modules.htxincailiao.analytics.domain.vo.HTPlatformVisitInfoVO;
import org.jeecg.modules.htxincailiao.analytics.domain.vo.HTPlatformVisitStatisticsVO;
import org.jeecg.modules.htxincailiao.analytics.entity.HTPlatformVisitAction;
import org.jeecg.modules.htxincailiao.analytics.service.IHTPlatformVisitActionService;
import org.jeecg.modules.htxincailiao.area.entity.HTArea;
import org.jeecg.modules.htxincailiao.area.service.IHTAreaService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: ht_platform_visit_action
 * @Author: jeecg-boot
 * @Date: 2022-05-07 10:18:56
 * @Version: V1.0
 */
@Api(tags = "ht_platform_visit_action")
@RestController
@RequestMapping("/analytics/hTPlatformVisitAction")
@Slf4j
public class HTPlatformVisitActionController extends JeecgController<HTPlatformVisitAction, IHTPlatformVisitActionService> {
    @Resource
    private IHTPlatformVisitActionService hTPlatformVisitActionService;

    @Resource
    private IHTAccountService accountService;

    @Resource
    private IHTAreaService areaService;

    /**
     * PV、UV数据查询
     *
     * @param req
     * @param beginTime
     * @param endTime
     * @return
     */
    @AutoLog(value = "ht_platform_visit_action-分页列表查询")
    @ApiOperation(value = "ht_platform_visit_action-分页列表查询", notes = "ht_platform_visit_action-分页列表查询")
    @GetMapping(value = "/getPVUVData")
    public Result<?> getPVUVData(HttpServletRequest req, String beginTime, String endTime) {
        List<HTPlatformVisitInfoVO> list = hTPlatformVisitActionService.getPVUVData(beginTime, endTime);
        return Result.OK(list);
    }

    /**
     * PV、UV数据查询
     *
     * @param req
     * @param beginTime
     * @param endTime
     * @return
     */
    @AutoLog(value = "ht_platform_visit_action-分页列表查询")
    @ApiOperation(value = "ht_platform_visit_action-分页列表查询", notes = "ht_platform_visit_action-分页列表查询")
    @GetMapping(value = "/getStatistics")
    public Result<?> getStatistics(HttpServletRequest req, String beginTime, String endTime) {
        HTPlatformVisitStatisticsVO vo = hTPlatformVisitActionService.getStatistics(beginTime, endTime);
        return Result.OK(JSONObject.parse(JSONObject.toJSONString(vo)));
    }

    /**
     * PV、UV 分布查询
     *
     * @param req       请求体
     * @param beginTime 开始时间
     * @param endTime   结束时间
     * @return pv、uv分布
     */
    @AutoLog(value = "ht_platform_visit_action-分页列表查询")
    @ApiOperation(value = "ht_platform_visit_action-分页列表查询", notes = "ht_platform_visit_action-分页列表查询")
    @GetMapping(value = "/getUserDistribution")
    public Result<?> getDistribution(HttpServletRequest req, String beginTime, String endTime) {
        List<HTPlatformUserVisitDistributionVO> list = hTPlatformVisitActionService.getUserDistribution(beginTime,
                endTime);
        return Result.OK(list);
    }

    /**
     * PV、UV 分布查询
     *
     * @param req       请求体
     * @param beginTime 开始时间
     * @param endTime   结束时间
     * @return pv、uv分布
     */
    @AutoLog(value = "ht_platform_visit_action-分页列表查询")
    @ApiOperation(value = "ht_platform_visit_action-分页列表查询", notes = "ht_platform_visit_action-分页列表查询")
    @GetMapping(value = "/getClientDistribution")
    public Result<?> getClientDistribution(HttpServletRequest req, String beginTime, String endTime) {
        List<HTPlatformClientVisitDistributionVO> list = hTPlatformVisitActionService.getClientDistribution(beginTime, endTime);
        return Result.OK(list);
    }

    /**
     * 分页列表查询
     * n
     *
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "ht_platform_visit_action-分页列表查询")
    @ApiOperation(value = "ht_platform_visit_action-分页列表查询", notes = "ht_platform_visit_action-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(HTPlatformVisitAction hTPlatformVisitAction,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<HTPlatformVisitAction> queryWrapper = QueryGenerator.initQueryWrapper(hTPlatformVisitAction, req.getParameterMap());
        Page<HTPlatformVisitAction> page = new Page<HTPlatformVisitAction>(pageNo, pageSize);
        IPage<HTPlatformVisitAction> pageList = hTPlatformVisitActionService.page(page, queryWrapper);
        return Result.OK(pageList);
    }


    /**
     * 添加
     *
     * @param hTPlatformVisitAction
     * @return
     */
    @AutoLog(value = "ht_platform_visit_action-添加")
    @ApiOperation(value = "ht_platform_visit_action-添加", notes = "ht_platform_visit_action-添加")
    @PostMapping(value = "/add")
    public Result<?> add(HttpServletRequest request, @RequestBody HTPlatformVisitAction hTPlatformVisitAction) throws URISyntaxException, IOException {
//        System.out.printf("\n\n\n hTPlatformVisitAction%s \n\n\n", JSONObject.toJSONString(hTPlatformVisitAction));
        String ip = IPUtil.getClientIp(request);
//        String ip = "182.149.201.158";
        IPInfo info = null;
        try {
//           info = IPUtil.getIPInfo("182.149.201.158");
            info = IPUtil.getIPInfo(ip);

        } catch (URISyntaxException ignored) {
        }


        Result<JSONObject> result = new Result<>();
        String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
        String username = null;
        if (oConvertUtils.isNotEmpty(token)) {
            username = JwtUtil.getUsername(token);
        }
        if (oConvertUtils.isNotEmpty(hTPlatformVisitAction.getClientOsString())) {
            Integer clientOs = HTClient.GetClientOsIndex(hTPlatformVisitAction.getClientOsString());
            hTPlatformVisitAction.setClientOs(clientOs);
        }

        HTPlatformUser user = null;
        if (oConvertUtils.isNotEmpty(username)) {
            user = accountService.queryFrontendUserByUsername(username);
        }

        if (oConvertUtils.isNotEmpty(user)) {
            hTPlatformVisitAction.setUserId(user.getId());
        }

        if (oConvertUtils.isNotEmpty(ip)) {
            hTPlatformVisitAction.setVisitIp(ip);
        }

        String provinceName = oConvertUtils.isNotEmpty(info) ? info.getProvinceName() : null;
        if (oConvertUtils.isNotEmpty(provinceName)) {
            List<HTArea> list = areaService.queryByName(provinceName);
            if (!list.isEmpty()) {
                HTArea area = list.stream().findFirst().orElse(null);
                if (oConvertUtils.isNotEmpty(area)) {
                    hTPlatformVisitAction.setProvinceId(area.getId());
                }
            }
        }
        String provinceId = hTPlatformVisitAction.getProvinceId();
        if (oConvertUtils.isNotEmpty(provinceId)) {
            List<HTArea> list = areaService.fuzzyQueryByName(provinceName);
            if (!list.isEmpty()) {
                HTArea area = list.stream().findFirst().orElse(null);
                if (oConvertUtils.isNotEmpty(area)) {
                    hTPlatformVisitAction.setProvinceId(area.getId());
                }
            }
        }

        if (hTPlatformVisitActionService.save(hTPlatformVisitAction)) {
            JSONObject obj = new JSONObject();
            obj.put("visitInfo", hTPlatformVisitAction);
            result.setResult(obj);

        } else {
            result.error500("保存访问日志失败");

        }
        return result;
    }

    /**
     * 编辑
     *
     * @param hTPlatformVisitAction
     * @return
     */
    @AutoLog(value = "ht_platform_visit_action-编辑")
    @ApiOperation(value = "ht_platform_visit_action-编辑", notes = "ht_platform_visit_action-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<?> edit(@RequestBody HTPlatformVisitAction hTPlatformVisitAction) {
        hTPlatformVisitActionService.updateById(hTPlatformVisitAction);
        return Result.OK("编辑成功!");
    }

    /**
     * 编辑
     *
     * @param body 请求参数
     * @return
     */
    @AutoLog(value = "ht_platform_visit_action-编辑")
    @ApiOperation(value = "ht_platform_visit_action-编辑", notes = "ht_platform_visit_action-编辑")
    @RequestMapping(value = "/visitEdit", method = {RequestMethod.POST})
    public Result<?> visitEdit(HttpServletRequest request, @RequestBody String body) throws IOException {
        HTPlatformVisitUpdateDTO dto = JSONObject.parseObject(body, HTPlatformVisitUpdateDTO.class);
        if (oConvertUtils.isNotEmpty(dto.getId())) {
            HTPlatformVisitAction htPlatformVisitAction = hTPlatformVisitActionService.getById(dto.getId());

            //  只更新需要更新的数据即可
            if (oConvertUtils.isNotEmpty(dto.getLeaveTime())) {
                htPlatformVisitAction.setLeaveTime(dto.getLeaveTime());
                hTPlatformVisitActionService.updateById(htPlatformVisitAction);
            }
        }


        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "ht_platform_visit_action-通过id删除")
    @ApiOperation(value = "ht_platform_visit_action-通过id删除", notes = "ht_platform_visit_action-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        hTPlatformVisitActionService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "ht_platform_visit_action-批量删除")
    @ApiOperation(value = "ht_platform_visit_action-批量删除", notes = "ht_platform_visit_action-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.hTPlatformVisitActionService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "ht_platform_visit_action-通过id查询")
    @ApiOperation(value = "ht_platform_visit_action-通过id查询", notes = "ht_platform_visit_action-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        HTPlatformVisitAction hTPlatformVisitAction = hTPlatformVisitActionService.getById(id);
        if (hTPlatformVisitAction == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(hTPlatformVisitAction);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param hTPlatformVisitAction
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HTPlatformVisitAction hTPlatformVisitAction) {
        return super.exportXls(request, hTPlatformVisitAction, HTPlatformVisitAction.class, "ht_platform_visit_action");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, HTPlatformVisitAction.class);
    }

}
